<!--
 * @Author: Cenven
 * @Date: 2021-06-29 11:43:33
 * @Description: 北京泓深教育发展有限公司
 * @Descripttion: 
 * @version: @Lastest
 * @LastEditTime: 2021-07-06 10:05:10
 * @CopyRight: 北京泓深教育发展有限公司
-->
<template>
  <div class="menu_simulation_component">
    <div class="simulation_container">
      <div class="title">
        <span>模拟考试</span>
        <span class="test_log" @click="showRecord = true">考试记录</span>
      </div>
      <div class="paper_list" v-if="paperList.length > 0">
        <div class="paper_item" @click="toStartTest(item)" v-for="(item, index) in paperList" :key="item.id">
          <div class="paper_name">
            <p>{{item.name}}</p>
            <Icon
              :type="openIndex == index ? 'ios-arrow-down' : 'ios-arrow-forward'"
              size="24"
              style="margin-right:20px;"
              @click.stop="openChangeHandle(index)"
            />
          </div>
          <div class="paper_info" v-if="index == openIndex">
            <p>题数：{{item.questionNum}}道&emsp;限时：{{item.span}}分钟&emsp;满分：{{item.total}}分</p>
            <p>考试时间：{{ formatDate(item.examinationStartDate) }} - {{ formatDate(item.examinationDeadlineDate) }}</p>
          </div>
        </div>
      </div>
      <div class="empty" v-else>
        <Icon type="ios-list-box" size="70" />
        <p>暂无试卷哟</p>
      </div>
    </div>
    <div class="record_test_fixed" v-show="showRecord">
      <div class="record_test_box">
        <h2 class="record_title">考试记录</h2>
        <Icon class="close_btn" type="md-close" size="24" @click="showRecord = false"/>
        <div class="test_record_list">
          <Table :columns="record_columns" :data="record_list" :height="height"></Table>
        </div>
      </div>
    </div>
    <Page
      v-if="total > 0"
      style="text-align:center;margin-top:30px;"
      :total="total"
      :current="page"
      :page-size="pageSize"
      @on-change="n=>pageChange(n)"
    ></Page>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import {
  getQuestionBankPaperList,
  getMyTestRecord,
} from "~/api/v2-question-bank/question-bank";
export default {
  name: "menu_simulation_component",
  props: ["questionId"],
  components: {},
  data() {
    const _this = this;
    return {
      openIndex:null,
      height:400,
      showRecord:false,
      page: 1,
      pageSize: 10,
      total: 0,
      paperList:[],
      /* 考试记录 */
      record_list: [],
      record_columns:[
          {
              title: '试卷名称',
              key: 'paperName',
              align:'center',
          },
          {
              title: '答对',
              key: 'name',
              width:120,
              align:'center',
              render(_, row) {
                return <span>{row.row.trueCount}/{row.row.allCount}</span>;
              }
          },
          {
              title: '用时',
              key: 'address',
              width:120,
              align:'center',
              render(_, row) {
                return <span>{row.row.useTime ? row.row.useTime + "分钟" : "未知"}</span>;
              }
          },
          {
              title: '考试时间',
              key: 'address',
              width:160,
              align:'center',
              render(_, row) {
                return <span>{_this.trimDate(row.row.createTime)}</span>;
              }
          },
          {
              title: '得分',
              key: 'address',
              width:120,
              align:'center',
              render(_, row) {
                const data = row.row;
                if(data.status == 2){
                  return <span>{ data.score || 0 }</span>;
                }else{
                  return <span>评分中</span>;
                }
              }
          },
          {
              title: '结果',
              key: 'address',
              width:120,
              align:'center',
              render(_, row) {
                const data = row.row;
                if(data.status == 2){
                  if(data.score >= data.passScore){
                    return <span style="color: #84d29f;">及格</span>;
                  }else{
                    return <span style="color: #f99797;">不及格</span>;
                  }
                }else{
                  return <span>未出</span>;
                }
              }
          },
      ],
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      question_record_list(state) {
        return state.questionBank.question_record_list;
      },
      kl_md(state) {
        return state.kl_md;
      }
    })
  },
  watch: {},
  methods: {
    ...mapMutations([
      "SET_IS_LOADING",
    ]),
    /* 格式化时间 */
    formatDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}年${_date.getMonth() +
          1}月${_date.getDate()}日`;
      } else {
        return this.$t("locale.components.mobile.GroupChat.t7");
      }
    },
    trimDate(time, pattern) {
        if (arguments.length === 0 || !time) {
            return null
        }
        const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
        let date
        if (typeof time === 'object') {
            date = time
        } else {
            if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
                time = parseInt(time)
            } else if (typeof time === 'string') {
                time = time.replace(new RegExp(/-/gm), '/');
            }
            if ((typeof time === 'number') && (time.toString().length === 10)) {
                time = time * 1000
            }
            date = new Date(time)
        }
        const formatObj = {
            y: date.getFullYear(),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            a: date.getDay()
        }
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
            let value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
            if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
            if (result.length > 0 && value < 10) {
                value = '0' + value
            }
            return value || 0
        })
        return time_str
    },
    openChangeHandle(i){
      if (this.openIndex == i) {
        this.openIndex = null;
      } else {
        this.openIndex = i;
      }
    },
    /* 获取考试记录 */
    async getExamRecord() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id,
        questionGroupId: this.questionId,
        type: 2,/* 试卷类型 1专项训练 2模拟考试 3真题训练 */
        sort:'id desc'
      };
      let result = await getMyTestRecord(params);
      // console.log("获取考试记录：", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows) {
          this.record_list = rows;
        }
      }
      this.SET_IS_LOADING(false);
    },
    /* 获取试卷状态 1正常 -1未开始  0已过期*/
    getTestPaperStatus(detail) {
      let current_date = new Date().getTime();
      let examinationStartDate = new Date(
        detail.examinationStartDate
      ).getTime();
      let examinationDeadlineDate = new Date(
        detail.examinationDeadlineDate
      ).getTime();
      if (
        examinationStartDate <= current_date &&
        current_date < examinationDeadlineDate
      ) {
        return 1;
      }
      if (examinationStartDate > current_date) {
        return -1;
      }
      if (examinationDeadlineDate < current_date) {
        return 0;
      }
    },
    /* 开始考试 */
    toStartTest(detail) {
      const { answerCount, testNum } = detail;
      if (answerCount == 0) {
        // console.log("可以无限考！");
      } else {
        if (testNum < answerCount) {
          // console.log(
          //   "已经考了" + testNum + "次；考次上限为" + answerCount + "次；"
          // );
        } else {
          this.$Message.warning("已达到考试上限次数！");
          return false;
        }
      }
      let status = this.getTestPaperStatus(detail);
      if (status == 0) {
        this.$Message.warning("已超过允许考试时间！");
        return false;
      } else if (status == -1) {
        this.$Message.warning("还没到考试时间哦！");
        return false;
      }
      this.$router.push({
        path: "/question-paper",
        query: {
          id: this.questionId,
          testId: detail.id,
          type: 2 /* 试卷类型 1专项训练 2模拟考试 3真题训练 */
        }
      });
    },
    /* 获取试卷列表 */
    async getPaperList() {
      this.SET_IS_LOADING(true);
      let params = {
        offset: (this.page - 1) * this.pageSize,
        limit: this.pageSize,
        questionGroupId: this.questionId,
        userId: this.user_info.id,
        type: 2,/* 试卷类型 1专项训练 2模拟考试 3真题训练 */
        sort:'id desc'
      };
      let result = await getQuestionBankPaperList(params);
      // console.log("获取试卷列表:", result);
      if (result && result.data && result.data.code == 200) {
        const { rows, total } = result.data.data;
        this.paperList = rows;
        this.total = total;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
      }
    },
    pageChange(n) {
      this.page = n;
      this.getPaperList();
    },
  },
  created() {
    this.getPaperList();
    this.getExamRecord();
  },
  mounted() {
    this.height = parseInt(window.innerHeight*0.8 - 70);
    window.addEventListener("resize", () => {
        this.height = parseInt(window.innerHeight*0.8 - 70);
    });
  }
};
</script>

<style lang="scss" scoped>
.menu_simulation_component {
  width: 100%;
  .simulation_container {
    box-sizing: border-box;
    padding: 20px 0px 20px 46px;
    background: #ffffff;
    .title {
      font-size: 18px;
      font-weight: bold;
      color: #5a5e66;
      border-bottom: 1px solid #e9edf5;
      line-height: 50px;
      background: #ffffff;
      position: relative;
      .test_log{
        position: absolute;
        right: 10px;
        top: 0;
        font-size: 16px;
        color: var(--theme-color);
        cursor: pointer;
      }
    }
    .paper_list {
      background: #ffffff;
      .paper_item {
        border-bottom: 1px solid #e9edf5;
        &:last-child {
          border-bottom: none;
        }
        .paper_name {
          width: 100%;
          height: 55px;
          font-size: 16px;
          font-weight: bold;
          color: #5a5e66;
          display: flex;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;
          p {
            width: 800px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .paper_info{
          padding: 10px;
          line-height: 30px;
          font-size: 14px;
        }
      }
    }
    .empty{
      padding: 30px;
      box-sizing: border-box;
      background: #ffffff;
      text-align: center;
      font-size: 16px;
    }
  }
  .record_test_fixed{
    position: fixed;
    z-index: 1424;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(55,55,55,.6);
    width: 100%;
    height: 100%;
    padding-bottom: 30px;
    box-sizing: border-box;
    .record_test_box{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      width: 60vw;
      height: 80vh;
      background: #ffffff;
      .record_title{
        line-height: 50px;
        font-size: 20px;
        font-weight: bold;
        text-align: center;
      }
      .close_btn{
        position: absolute;
        right: 10px;
        top: 10px;
        cursor: pointer;
      }
      .test_record_list{
        height: calc(100% - 70px);
        box-sizing: border-box;
        overflow: auto;
      }
    }
  }
}
</style>
